const secp256k1 = require('secp256k1');
const { keccak256 } = require('ethereumjs-util');
const { randomBytes } = require('crypto');

let num = [];
// 批量生成地址
function generateAddresses(count) {
    const addresses = [];
    for (let i = 0; i < count; i++) {
        try {
            // 生成随机私钥
            let privateKey;
            do {
                privateKey = randomBytes(32);
            } while (!secp256k1.privateKeyVerify(privateKey));

            // 生成公钥
            const publicKey = secp256k1.publicKeyCreate(privateKey, false).slice(1);

            // 确保公钥是 Buffer 类型
            const publicKeyBuffer = Buffer.from(publicKey);

            // 生成地址
            const address = keccak256(publicKeyBuffer).slice(-20);
            addresses.push({
                privateKey: privateKey.toString('hex'),
                address: '0x' + address.toString('hex')
            });
        } catch (error) {
            console.error('Error generating address:', error);
        }
    }
    num.push(addresses);
    return addresses;
}

function createAddress(i) {
    return new Promise((resolve, reject) => {
        console.log(`线程${i}开始执行`);
        while(!isSuccess){
            const addr = generateAddresses(1);
            const address = addr[0].address;
            const privateKey = addr[0].privateKey;
            if (address.substring(address.length-4,address.length) == '88888'){
                isSuccess = true;
                console.log('Address:', address);
                console.log('Private Key:', privateKey);
                resolve()
            }
        }
    })

}

let isSuccess = false;
async function startClick(num = 4){
    const loops = [];
    for(let i = 0; i < num; i++){
        loops.push(createAddress(i.toString()));
    }
    await Promise.race(loops);
}

module.exports = {
    startClick,
    generateAddresses
}